<?php

namespace Easy;

use Easy\Db\DbDTO;
use Easy\Exception\LogicError;

class DbContainer
{
    private static $_db;

    private static $_trans=[];

    public static function regist(DbDTO $dbDTO, $instanceName = '')
    {
        $instanceName             = empty($instanceName) ? 0 : $instanceName;
        self::$_db[$instanceName] = EasyDb::instance($dbDTO);
    }

    public static function get($instanceName = '')
    {
        $instanceName = empty($instanceName) ? 0 : $instanceName;
        if (!self::$_db[$instanceName]) {
            throw new LogicError($instanceName . ' not regist');
        }

        return self::$_db[$instanceName];
    }

    public static function startTrans($instanceName = '')
    {
        $instanceName = empty($instanceName) ? 0 : $instanceName;
        if (!isset(self::$_trans[$instanceName])) {
            $db                          = self::get($instanceName);
            self::$_trans[$instanceName] = $db;
            $db->startTrans();
        }
    }

    public static function rollBack()
    {
        foreach (self::$_trans as $v) {
            $v->rollback();
        }
    }

    public static function commitTrans()
    {
        foreach (self::$_trans as $v) {
            $v->commit();
        }
    }


}